/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.webapp.security;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
abstract public class HttpRequestContext {
    @NonNull @Getter private HttpServletRequest request;
    @NonNull @Getter private HttpServletResponse response;

    private String remoteAddress = null;
    private SecurityCookieManager cookieManager = null;

    public synchronized String getRemoteAddress() {
        if (remoteAddress != null) {
            return remoteAddress;
        }

        String remoteAddr = this.request.getRemoteAddr();
        remoteAddress = remoteAddr;
        boolean useHttpHeaderRemoteAddr = false;

        if (remoteAddr == null) {
            useHttpHeaderRemoteAddr = true;
        } else {
            if (remoteAddr.startsWith("10.") || remoteAddr.startsWith("192.168.") || remoteAddr.startsWith("127.0.0.")) {
                useHttpHeaderRemoteAddr = true;
            }
        }

        if (useHttpHeaderRemoteAddr) {
            String ip = this.request.getHeader("X-Real-IP");
            if (ip == null) {
                ip = this.request.getHeader("X-Forwarded-For");
            }
            if (ip != null)
                remoteAddress = ip;
        }

        if (remoteAddress == null) {
            remoteAddress = "0.0.0.0";  //damn it, no ip at all?
        }
        return remoteAddress;
    }

    public synchronized SecurityCookieManager getCookieManager() {
        if (cookieManager != null) {
            return cookieManager;
        }
        cookieManager = new SecurityCookieManager(request, response);
        return cookieManager;
    }

    public void redirect(String location) throws IOException {
        response.sendRedirect(location);
    }
}
